import React, { useState, useRef, useEffect } from 'react';
import { Button, Card, TerminalIcon } from "@repo/ui";
import styles from './TerminalPage.module.css';

interface TerminalLine {
  id: string;
  content: string;
  type: 'input' | 'output' | 'error';
  timestamp: Date;
}

const TerminalPage: React.FC = () => {
  const [lines, setLines] = useState<TerminalLine[]>([
    {
      id: '1',
      content: 'ESP32 终端模拟器已启动...',
      type: 'output',
      timestamp: new Date()
    }
  ]);
  const [currentInput, setCurrentInput] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [isConnecting, setIsConnecting] = useState(false);
  const terminalRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
    }
  }, [lines]);

  const addLine = (content: string, type: TerminalLine['type']) => {
    const newLine: TerminalLine = {
      id: Date.now().toString(),
      content,
      type,
      timestamp: new Date()
    };
    setLines(prev => [...prev, newLine]);
  };

  const handleConnect = async () => {
    setIsConnecting(true);
    addLine('正在连接ESP32设备...', 'output');
    
    setTimeout(() => {
      if (Math.random() > 0.3) {
        setIsConnected(true);
        addLine('✓ ESP32设备连接成功', 'output');
        addLine('设备信息: ESP32-WROOM-32', 'output');
        addLine('固件版本: v4.4.2', 'output');
      } else {
        addLine('✗ 连接失败：设备未找到', 'error');
      }
      setIsConnecting(false);
    }, 2000);
  };

  const handleDisconnect = () => {
    setIsConnected(false);
    addLine('设备连接已断开', 'output');
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!currentInput.trim()) return;

    addLine(`> ${currentInput}`, 'input');

    if (!isConnected) {
      addLine('错误：设备未连接', 'error');
      setCurrentInput('');
      return;
    }

    const command = currentInput.toLowerCase().trim();
    
    setTimeout(() => {
      switch (command) {
        case 'help':
          addLine('可用命令:', 'output');
          addLine('  help     - 显示帮助信息', 'output');
          addLine('  status   - 显示设备状态', 'output');
          addLine('  reset    - 重启设备', 'output');
          addLine('  wifi     - WiFi设置', 'output');
          addLine('  clear    - 清空终端', 'output');
          break;
        case 'status':
          addLine('设备状态:', 'output');
          addLine('  芯片: ESP32', 'output');
          addLine('  内存: 520KB SRAM', 'output');
          addLine('  Flash: 4MB', 'output');
          addLine('  WiFi: 已连接', 'output');
          break;
        case 'reset':
          addLine('正在重启设备...', 'output');
          setTimeout(() => {
            addLine('设备重启完成', 'output');
          }, 1500);
          break;
        case 'wifi':
          addLine('WiFi状态: 已连接', 'output');
          addLine('SSID: ESP32_Network', 'output');
          addLine('IP: 192.168.1.100', 'output');
          break;
        case 'clear':
          setLines([]);
          break;
        default:
          addLine(`未知命令: ${command}`, 'error');
          addLine('输入 "help" 查看可用命令', 'output');
      }
    }, 500);

    setCurrentInput('');
  };

  const handleClear = () => {
    setLines([]);
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.title}>
          <TerminalIcon size={20} className={styles.titleIcon} />
          <h1>ESP32 终端</h1>
          <div className={`${styles.status} ${isConnected ? styles.connected : ''}`}>
            <div className={styles.statusDot}></div>
            <span>{isConnected ? '已连接' : '未连接'}</span>
          </div>
        </div>
        
        <div className={styles.controls}>
          <Button 
            onClick={handleClear}
            variant="outline"
            size="sm"
          >
            清空
          </Button>
          {isConnected ? (
            <Button 
              onClick={handleDisconnect}
              variant="destructive"
              size="sm"
            >
              断开连接
            </Button>
          ) : (
            <Button 
              onClick={handleConnect}
              disabled={isConnecting}
              size="sm"
            >
              {isConnecting ? '连接中...' : '连接设备'}
            </Button>
          )}
        </div>
      </div>

      <Card className={styles.terminalCard}>
        <div className={styles.terminal} ref={terminalRef}>
          <div className={styles.content}>
            {lines.map((line) => (
              <div 
                key={line.id} 
                className={`${styles.line} ${styles[line.type]}`}
              >
                <span className={styles.timestamp}>
                  {line.timestamp.toLocaleTimeString()}
                </span>
                <span className={styles.text}>{line.content}</span>
              </div>
            ))}
            
            {isConnected && (
              <form onSubmit={handleSubmit} className={styles.inputLine}>
                <span className={styles.prompt}>ESP32 $</span>
                <input
                  ref={inputRef}
                  type="text"
                  value={currentInput}
                  onChange={(e) => setCurrentInput(e.target.value)}
                  className={styles.input}
                  placeholder="输入命令..."
                  autoFocus
                />
              </form>
            )}
          </div>
        </div>
      </Card>

      <div className={styles.footer}>
        <div className={styles.tips}>
          <span>提示：输入 "help" 查看可用命令</span>
        </div>
      </div>
    </div>
  );
};

export default TerminalPage;
